package com.miniot.pest.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miniot.pest.entity.EquipmentDetail;
import com.miniot.pest.entity.EquipmentRecognize;
import com.miniot.pest.mapper.EquipmentRecognizeMapper;
import com.miniot.pest.service.EquipmentDetailService;
import com.miniot.pest.service.EquipmentRecognizeService;
import com.miniot.pest.vo.EquipmentDetailVO;
import com.miniot.pest.vo.EquipmentRecognizeVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 仓库表
 *
 * @author zzq
 * @date 2023-10-20 09:45:25
 */
@Service
@AllArgsConstructor
@Slf4j
public class EquipmentRecognizeServiceImpl extends ServiceImpl<EquipmentRecognizeMapper, EquipmentRecognize> implements EquipmentRecognizeService {

    private final EquipmentDetailService equipmentDetailService;

    @Override
    @Transactional
    public boolean saveEquipmentRecognize(EquipmentRecognizeVO equipmentRecognize) {
        EquipmentRecognize equipmentRecognize1 = new EquipmentRecognize();
        Long id=null;
        List<EquipmentDetailVO> equipmentDetailVOS = equipmentRecognize.getEquipmentDetailVOS();
        if (ObjectUtil.isNotEmpty(equipmentRecognize)){
            // TODO 用设备code查设备 set设备名   未做
            BeanUtil.copyProperties(equipmentRecognize,equipmentRecognize1);
            Integer sum=null;
            for (EquipmentDetailVO vo : equipmentDetailVOS){
                sum+=vo.getSubtotal();
                EquipmentDetail equipmentDetail = new EquipmentDetail();
                BeanUtil.copyProperties(vo,equipmentDetail);
            }
            equipmentRecognize1.setTotalNumber(sum);
            this.save(equipmentRecognize1);
            id=equipmentRecognize1.getId();
            List<EquipmentDetail> equipmentDetails = new ArrayList<>();
            for (EquipmentDetailVO vo : equipmentDetailVOS){
                EquipmentDetail equipmentDetail = new EquipmentDetail();
                BeanUtil.copyProperties(vo,equipmentDetail);
                equipmentDetails.add(equipmentDetail);
            }
            equipmentDetailService.saveBatch(equipmentDetails);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean removeRecognizeById(Long id) {
        if (ObjectUtil.isEmpty(id)){
            throw new RuntimeException("id不能为空");
        }
        this.removeById(id);
        equipmentDetailService.remove(new LambdaQueryWrapper<EquipmentDetail>().eq(EquipmentDetail::getEquipmentRecognizeId,id));
        return true;
    }
}
